
import hashlib
import random
import uuid
from passlib.handlers.pbkdf2 import pbkdf2_sha256


class StringUtil:
    
    @staticmethod
    def gen_password(password:str, salt:str):
        return StringUtil.md5(StringUtil.md5(password) + ":" + salt)
    
    @staticmethod
    def md5(s:str):
        return hashlib.md5(s.encode(encoding='UTF-8')).hexdigest()
        
        
    @staticmethod
    def random_str():
        """
        唯一随机字符串
        :return: str
        """
        only = hashlib.md5(str(uuid.uuid1()).encode(encoding='UTF-8')).hexdigest()
        return str(only)

    @staticmethod
    def en_password(psw: str):
        """
        密码加密
        :param psw: 需要加密的密码
        :return: 加密后的密码
        """
        password = pbkdf2_sha256.hash(psw)
        return password

    @staticmethod
    def check_password(password: str, old: str):
        """
        密码校验
        :param password: 用户输入的密码
        :param old: 数据库密码
        :return: Boolean
        """
        check = pbkdf2_sha256.verify(password, old)
        if check:
            return True
        else:
            return False

    @staticmethod
    def code_number(ln: int):
        """
        随机数字
        :param ln: 长度
        :return: str
        """
        code = ""
        for i in range(ln):
            ch = chr(random.randrange(ord('0'), ord('9') + 1))
            code += ch

        return code
